package com.wasion.pwportable.protocol;

import com.wasion.pwportable.protocol.analyzer.AnalyzerFactory;
import com.wasion.pwportable.protocol.analyzer.AnalyzerIF;

/**
 * @className InFramer.java
 * @author lijian
 * @description 收到的帧的预处理器
 * @date 2014-5-7
 * 
 */
public class InFramer {

	private static InFramer instance = null;

	public synchronized static InFramer getInstance() {
		if (instance == null) {
			instance = new InFramer();
		}
		return instance;
	}

	private String senderIdentifier;

	private String frame;

	private InFramer() {

	}

	/**
	 * 
	 * @desc 判断是不是一个合法的帧
	 * @date 2014-5-7
	 * @author lijian
	 * @return String
	 */
	public boolean validateFrame() {
		StringBuffer buffer = new StringBuffer(frame);
		if (buffer.substring(0, 2).equalsIgnoreCase(Protocol.FRAEMHEAD)
				&& (buffer.substring(buffer.length() - 2, buffer.length())
						.equalsIgnoreCase(Protocol.FRAMETAIL))) {
			return true;
		} else
			return false;
	}

	/**
	 * @desc 对帧处理
	 * @date 2014-5-7
	 * @author lijian
	 * @return String
	 */
	public Result process() {

		AnalyzerFactory factory = AnalyzerFactory.getFactory();

		// 根据功能标识产生对应的解析器实例
		AnalyzerIF analyzer = factory.getAnalyzer(senderIdentifier);
		if (null == analyzer) {
			return null;
		}
		analyzer.setActionId(senderIdentifier);
		// 返回处理结果
		return analyzer.analyze(frame);

	}

	/**
	 * @desc 读入功能标识符，用来判断帧是不是对应
	 * @date 2014-5-7
	 * @author lijian
	 * @return String
	 */
	public void setIdentifier(String identifier) {
		senderIdentifier = identifier;
	}

	public boolean isRightIdentifier() {

		String identifier = frame.substring(Protocol.DATATPYESTARTBIT,
				Protocol.DATATPYENDBIT);

		if (!senderIdentifier.equalsIgnoreCase(identifier)) {
			// logger.info("收到一个错误帧！ ");
			return false;
		} else
			return true;

	}

	public String getFrame() {
		return frame;
	}

	public void setFrame(String frame) {
		this.frame = frame;
	}

}
